package com.coocaa.aries.jmeter.util;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.Namespace;
import org.jdom2.input.SAXBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.List;

/**
 * @author : bijiahao
 * @date : 2019/4/15.
 * @description:<p> </p>
 */
public class XmlUtil {
    public static final String FILE_SEP = "/";
    private static final Logger log = LoggerFactory.getLogger(XmlUtil.class);
    private String filepath;
    private Document document;


    public XmlUtil(String filepath, Boolean isFileName) {
        this.filepath = filepath;
        loadFile();
    }

    public XmlUtil(File file) {
        try {
            this.filepath = file.getAbsolutePath();
            InputStreamReader in = new InputStreamReader(new FileInputStream(file), "UTF-8");
            loadReader(in);
        } catch (Exception e) {
            StringBuilder sb = new StringBuilder();
            sb.append("====加载配置文件: ")
                    .append(this.filepath)
                    .append("，异常");
            log.error(sb.toString());
        }
    }

    public static void main(String[] args) {
        String filepath = "/Users/bijiahao/develop/jmeter/tttttt.jmx.xml";
        XmlUtil xmlUtil = new XmlUtil(new File(filepath));

        List<Element> list = xmlUtil.listEleByNodeName("ThreadGroup");


        Element root = xmlUtil.getRootEle();

        root.getNamespace();

        root.getChild("ThreadGroup", Namespace.getNamespace(""));


    }

    /**
     * 加载文件
     */
    private void loadFile() {
        try {
            //获取配置文件 输入流
            InputStreamReader in = new InputStreamReader(this.getClass().getResourceAsStream(FILE_SEP + this.filepath), "UTF-8");
            loadReader(in);
        } catch (Exception e) {
            StringBuilder sb = new StringBuilder();
            sb.append("====加载配置文件: ")
                    .append(this.filepath)
                    .append("，异常");
            log.error(sb.toString());
        }
    }

    private synchronized void loadReader(InputStreamReader in) {
        SAXBuilder saxBuilder = new SAXBuilder();
        try {
            this.document = saxBuilder.build(in);
        } catch (Exception e) {
            StringBuilder sb = new StringBuilder();
            sb.append("\n====解析配置文件: ")
                    .append(this.filepath)
                    .append("，异常");
            log.error(sb.toString());
        }
    }

    public Element getRootEle() {
        return document.getRootElement();
    }

    public List<Element> listEleByNodeName(String nodeName) {
        return getRootEle().getChildren(nodeName);
    }

    public Document getDocument() {
        return this.document;
    }
}
